// tools/audit-gm/alarm.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <time.h>
#include <syslog.h>
#include <errno.h>

static void ensure_dir(const char *dir) {
    struct stat st;
    if (stat(dir, &st) == -1) {
        mkdir(dir, 0755);
    }
}

void trigger_alarm(const char *message) {
    if (!message) return;

    // 1) stderr
    fprintf(stderr, "[ALARM] %s\n", message);

    // 2) 本地日志文件
    ensure_dir("/var/log/audit-gm");
    FILE *f = fopen("/var/log/audit-gm/alarm.log", "a");
    if (f) {
        time_t t = time(NULL);
        struct tm tm; localtime_r(&t, &tm);
        char ts[64];
        strftime(ts, sizeof(ts), "%F %T", &tm);
        fprintf(f, "%s %s\n", ts, message);
        fclose(f);
    } else {
        fprintf(stderr, "[ALARM] open /var/log/audit-gm/alarm.log failed: %s\n", strerror(errno));
    }

    // 3) syslog
    openlog("audit-alarm", LOG_PID|LOG_CONS, LOG_AUTH);
    syslog(LOG_ALERT, "%s", message);
    closelog();
}
